<template>
    <div>
        <div class="city-search">
            <input v-model="keyWord" class="search-input" type="text" placeholder="输入城市名或拼音">
        </div>
        <div class="search-list" v-show="keyWord" ref="search">
            <ul>
                <li v-for="item in list" :key="item.id" @click="updateCity(item.name)">{{ item.name }}</li>
                <li v-show="hasNoData">没有查询到该城市</li>
            </ul>
        </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
    name: 'CitySearch',
    props: {
        cities: Object
    },
    data() {
        return {
            keyWord: '',
            timer: null,
            list: []
        }
    },
    methods: {
        updateCity(val) {
            // this.$store.commit('changeCity', val)
            // 利用...mapMutations映射changeCity方法
            this.changeCity(val)

            // 选择完城市之后清空搜索关键词
            this.keyWord = ''
            this.$router.push({
                path: '/'
            })
        },
        ...mapMutations(['changeCity'])
    },
    computed: {
        hasNoData() {
            return !this.list.length
        }
    },
    watch: {
        keyWord() {
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                const result = []
                for (let i in this.cities) {
                    this.cities[i].forEach((val) => {
                        if (val.spell.indexOf(this.keyWord) > -1 || val.name.indexOf(this.keyWord) > -1) {
                            result.push(val)
                        }
                    })
                }
                this.list = result
            }, 100)
        }
    },
    mounted() {
        this.scroll = new Bscroll(this.$refs.search)
    }
}
</script>

<style lang="scss" scoped>
@import '~styles/varibles.scss';
.city-search{
    height: 0.72rem;
    padding: 0 0.1rem;
    background: $bgColor;
    .search-input{
        box-sizing: border-box;
        width: 100%;
        height: 0.62rem;
        line-height: 0.62rem;
        text-align: center;
        border-radius: 0.06rem;
        padding: 0 0.1rem;
    }
}
.search-list{
    overflow: hidden;
    z-index: 1;
    position: absolute;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    li{
        background: #fff;
        padding: 0 0 0 0.2rem;
        line-height: 0.68rem;
    }
}
</style>
